package com.wlf.server.common.service;

import cn.hutool.core.io.FileUtil;
import com.wlf.server.common.config.FileConfig;
import com.wlf.server.common.context.BeanContext;
import com.wlf.server.common.entity.SysAttachment;
import com.wlf.server.common.service.iservice.FileUploadService;
import com.wlf.server.web.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDate;

@Slf4j
@Service
public class FileUploadServiceLocalImpl implements FileUploadService {
    @Resource
    FileConfig.LocalFileConfig localFileConfig;

    /**
     * 上传文件
     *
     * @param file   文件
     * @param remark 文件备注
     * @return 返回
     */
    @Override
    public SysAttachment plus(MultipartFile file, String remark) {
        SysAttachment attachment = initAttachment(file);
        attachment.setFileSrc(FileConfig.FileType.local.name());
        String filePath = localFileConfig.getAttachmentPath() + "/" + LocalDate.now() + "/" + attachment.getFilename();
        File ioFile = new File(filePath);
        FileUtil.mkParentDirs(ioFile);
        try {
            file.transferTo(ioFile);
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败：" + e);
        }
        attachment.setAbsolutePath(filePath);
        attachment.setWebPath(localFileConfig.getWebPath() + "/" + LocalDate.now() + "/" + attachment.getFilename());
        attachment.setRemark(remark);
        return attachment;
    }

    /**
     * 删除文件
     *
     * @param id 文件Id
     */
    @Override
    public void del(String id) {
        // 先删除本地文件
        SysAttachment attachment = BeanContext.getBean(SysAttachmentService.class).getById(id);
        //如果文件不存在
        if (attachment != null && attachment.getAbsolutePath() != null) {
            File deleteFile;
            if ((deleteFile = new File(attachment.getAbsolutePath())).exists()) {
                try {
                    Files.delete(deleteFile.toPath());
                } catch (IOException e) {
                    log.warn("fileId:{} ,need delete filePath:{} not exists ", id, attachment.getAbsolutePath());
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param id 文件Id
     */
    @Override
    public void read(String id) {
        try {
            SysAttachment attachment = BeanContext.getBean(SysAttachmentService.class).getById(id);
            if (null == attachment) {
                attachment = new SysAttachment();
                attachment.setAbsolutePath("");
            }
            File files = new File(attachment.getAbsolutePath());
            if (files.exists()) {
                HttpServletResponse response = ServletUtil.getResponse();
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                        ContentDisposition.attachment().filename(
                                        attachment.getOriginalFilename(), StandardCharsets.UTF_8)
                                .build().toString()
                );
                FileCopyUtils.copy(new FileInputStream(files), response.getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取附件失败", e);
        }
    }
}
